package org.ats.mail;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

@Service("MailListener")
public class MailListener implements MessageListener {
	
	@Autowired
	ApplicationContext context;
	
	@Autowired
	private JmsTemplate atsJmsTemplate;
	
	@Autowired
	private AtsMailPreperator atsMailPreperator;
	
	@Autowired
	private AtsMailSender atsMailSender;

	public ApplicationContext getContext() {
		return context;
	}

	public void setContext(ApplicationContext context) {
		this.context = context;
	}

	public void setAtsJmsTemplate(JmsTemplate atsJmsTemplate) {
		this.atsJmsTemplate = atsJmsTemplate;
	}

	public void setAtsMailPreperator(AtsMailPreperator atsMailPreperator) {
		this.atsMailPreperator = atsMailPreperator;
	}

	public JmsTemplate getAtsJmsTemplate() {
		return atsJmsTemplate;
	}

	public AtsMailPreperator getAtsMailPreperator() {
		return atsMailPreperator;
	}

	@Override
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		if (msg instanceof ObjectMessage){
			try {
				MailContent mc = (MailContent) ((ObjectMessage) msg).getObject();
				System.out.println("JMS msg Recieved " + mc.getSubject());
				setAtsMailPreperator((AtsMailPreperator) getContext().getBean("AtsMailPreperator"));
				getAtsMailPreperator().PrepareMIMEMsg(mc);
				atsMailSender.sendMsg(getAtsMailPreperator().getMime());
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
